package org.flik.server.bean;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.flik.server.dto.TicketChange;
import org.flik.server.entity.FlikUser;
import org.flik.server.entity.Project;
import org.flik.server.entity.Ticket;
import org.flik.server.entity.TicketComment;
import org.flik.server.entity.TicketStatus;
import org.flik.server.entity.TicketType;

@Stateless
@LocalBean
public class TicketDetailBean {

	@PersistenceContext
	private EntityManager em;
	
	public void save(final TicketChange ticketChange, Long loggedInUserId) {
		Ticket ticket = em.find(Ticket.class, ticketChange.getTicketId());
		if (ticketChange.getTicketTypeId() != null)
			ticket.setTicketType(em.find(TicketType.class, ticketChange.getTicketTypeId()));
		if (ticketChange.getStatusId() != null)
			ticket.setTicketStatus(em.find(TicketStatus.class, ticketChange.getStatusId()));
		if (ticketChange.getAssignedToId() != null)
			ticket.setAssignee(em.find(FlikUser.class, ticketChange.getAssignedToId()));
		if (ticketChange.getComment() != null && !ticketChange.getComment().equals("")){
			TicketComment tc = new TicketComment(
					em.find(FlikUser.class, loggedInUserId), 
					ticketChange.getComment(), null, ticket);
			TicketComment replyTo = em.find(TicketComment.class, ticket.getTicketComment().getId());
			tc.setReplyTo(replyTo);
			em.persist(tc);
		}
		if (!isOnlyCommentChanged(ticketChange))
			em.merge(ticket);
	}
	private boolean isOnlyCommentChanged(TicketChange ticketChange){
		return ticketChange.getTicketTypeId() == null && ticketChange.getAssignedToId() == null && ticketChange.getStatusId() == null && ticketChange.getComment() != null;
	}
	public Long create(TicketChange ticketChange, Long loggedInUserId, Long projectId) {
		FlikUser reportedBy = em.find(FlikUser.class, loggedInUserId);
		TicketType ticketType = em.find(TicketType.class, ticketChange.getTicketTypeId());
		TicketStatus ticketStatus = em.find(TicketStatus.class, ticketChange.getStatusId());
		FlikUser asignee = em.find(FlikUser.class, ticketChange.getAssignedToId());
		Project project = em.find(Project.class, projectId);
		Ticket ticket = new Ticket(reportedBy, ticketType, ticketStatus, asignee, project, ticketChange.getTitle(), null);
		em.persist(ticket);
		TicketComment tc = new TicketComment(
				em.find(FlikUser.class, loggedInUserId), 
				ticketChange.getComment(), null, ticket);
		em.persist(tc);
		ticket.setTicketComment(tc);
		em.merge(ticket);
		return ticket.getId();
	}
	
}

